package com.itheima.service.Impl;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.common.BaseContext;
import com.itheima.common.CustomException;
import com.itheima.dao.OrderDetailMapper;
import com.itheima.dao.OrdersMapper;
import com.itheima.pojo.*;
import com.itheima.service.*;
import org.apache.ibatis.javassist.bytecode.CodeIterator;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.management.OperationsException;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

@Service
public class OrdersServiceImpl extends ServiceImpl<OrdersMapper, Orders> implements OrdersService {
    @Autowired
    private ShoppingCartService shoppingCartService;
    @Autowired
    private UserService userService;
    @Autowired
    private AddressBookService addressBookService;
    @Autowired
    private OrderDetailService orderDetailService;

    @Transactional
    @Override
    public void submit(Orders orders) {
        //获取当前等的id
        Long userId = BaseContext.getCurrentId();

        //查购物车用户
        LambdaQueryWrapper<ShoppingCart> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ShoppingCart::getUserId,userId);
        List<ShoppingCart> list = shoppingCartService.list(wrapper);
        //如果购物车里没数据就不能下单
        if(list == null || list.size()==0){
            throw new CustomException("购物车为空，不能下单");
        }
        //查询用户数据
        User user = userService.getById(userId);
        //查询地址数据
        Long addressBookId = orders.getAddressBookId();
        AddressBook addressBook = addressBookService.getById(addressBookId);
        //判度地址
        if (addressBook==null){
            throw  new CustomException("地址为空，不能下单");
        }
        long orderId = IdWorker.getId();//订单号
        //创建单个金额对象
        AtomicInteger amount = new AtomicInteger(0);
        //遍历购物车的数据集合
       List<OrderDetail>  OrderDetail= list.stream().map((item)->{
           OrderDetail orderDetail = new OrderDetail();
           orderDetail.setOrderId(orderId);
           orderDetail.setNumber(item.getNumber());
           orderDetail.setDishFlavor(item.getDishFlavor());
           orderDetail.setDishId(item.getDishId());
           orderDetail.setSetmealId(item.getSetmealId());
           orderDetail.setName(item.getName());
           orderDetail.setImage(item.getImage());
           orderDetail.setAmount(item.getAmount());
           //addAndGet累加 =单个金额multiply（乘）份数BigDecimal（份数对象）转成int
           //Name是名字  Number才是数量
           amount.addAndGet(item.getAmount().multiply(new BigDecimal(item.getNumber())).intValue());
           //返回订单明细表数据
           return orderDetail;

       }).collect(Collectors.toList());


        //存储订单数据
        orders.setId(orderId);
        orders.setNumber(String.valueOf(orderId));
        orders.setStatus(2);
        orders.setUserId(userId);
        orders.setOrderTime(LocalDateTime.now());
        orders.setAmount(new BigDecimal(amount.get()));
        orders.setCheckoutTime(LocalDateTime.now());
        orders.setUserName(addressBook.getConsignee());
        orders.setConsignee(addressBook.getConsignee());
        orders.setPhone(addressBook.getPhone());
        orders.setAddress((addressBook.getProvinceName()==null?"": addressBook.getProvinceName())
                        +(addressBook.getCityName()==null?"":addressBook.getCityName())
                        +(addressBook.getDistrictName()==null?"":addressBook.getDistrictName())
                        +(addressBook.getDetail()==null?"":addressBook.getDetail()));
        //向订单表添加一条数据
        this.save(orders);

        //向订单明细表添加所有数据
        orderDetailService.saveBatch(OrderDetail);

        //清空购物车
        shoppingCartService.remove(wrapper);
    }


//    @Override
//    public void exportData(HttpServletResponse response) throws IOException {
//        List<Orders> list = new ArrayList<>();
//        for (Orders orders : list) {
//            System.out.println(orders.toString());
//        }
//        response.setHeader("Content-Disposition", "attachment;filename=test1.xlsx");
//// easyexcel 进行浏览器响应返回excel 。class的文件， 子sheet是ceshi   表明是test1   数据是excelList
//        EasyExcel.write(response.getOutputStream(),Orders.class)
//                .sheet("ceshi")
//                .doWrite(list);
//    }
}
